<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="「优先队列」专题 2：堆排序、heapify、原地堆排序, 算法与数据结构入门教程">
    <meta name="description" content="Java、Python3 语言实现，「专题」教程持续更新中...">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>「优先队列」专题 2：堆排序、heapify、原地堆排序 | 算法与数据结构入门教程</title>
    <link rel="icon" type="image/png" href="/leetcode-algo/favicon.png">

    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/my.css">

    <script src="/leetcode-algo/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/leetcode-algo/atom.xml" title="算法与数据结构入门教程" type="application/atom+xml">
<link rel="stylesheet" href="/leetcode-algo/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/leetcode-algo/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/leetcode-algo/" class="waves-effect waves-light">
                    
                    <img src="/leetcode-algo/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">算法与数据结构入门教程</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/leetcode-algo/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">算法与数据结构入门教程</div>
        <div class="logo-desc">
            
            Java、Python3 语言实现，「专题」教程持续更新中...
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/leetcode-algo/medias/featureimages/15.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">「优先队列」专题 2：堆排序、heapify、原地堆排序</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/leetcode-algo/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    .toc-fixed .toc-link::before{
        position: fixed!important;/*当toc的位置改为fixed时，.toc-link::before也要改为fixed*/
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/leetcode-algo/tags/%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97/">
                                <span class="chip bg-color">优先队列</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-10%EF%BC%9A%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97/" class="post-category">
                                专题 10：优先队列
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2017-10-02
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="「队列」专题-2：堆排序、heapify、原地堆排序"><a href="#「队列」专题-2：堆排序、heapify、原地堆排序" class="headerlink" title="「队列」专题 2：堆排序、heapify、原地堆排序"></a>「队列」专题 2：堆排序、heapify、原地堆排序</h2><p>说明：</p>
<blockquote>
<p>以下出现 <code>sift down</code> 的地方有可能写作 <code>shift down</code>，还有可能写作 <code>sink</code> ，它们都表示「下沉」的意思；</p>
<p>同理，出现 <code>sift up</code> 的地方有可能写作 <code>shift up</code>，还有可能写作 <code>swim</code> ，它们都表示「上浮」的意思；</p>
<p>因为我个人的原因，给大家造成不便，请各位谅解。</p>
</blockquote>
<p>以下说明来自 liuyubobobo 对于问题：<a href="https://coding.imooc.com/learn/questiondetail/111370.html" target="_blank" rel="noopener">《请问到底是sift down 还是shift down》</a> 的回复，我做了删改。</p>
<blockquote>
<p>补充说明：对于命名：推荐用 <code>sift</code>。 参见 wiki 百科：<a href="https://en.wikipedia.org/wiki/Binary_heap" target="_blank" rel="noopener">https://en.wikipedia.org/wiki/Binary_heap</a> 。</p>
<p>由于 <code>sift</code> 和 <code>shift</code> 拼写很接近，取 <code>shift</code> 的意思，没什么不妥的（甚至更贴切），所以很多资料也是使用 <code>shift</code>。在理解上，不会有歧义。或许是为了消除这个歧义，很多教材，会避免使用 sift/shift 的用法。比如大名鼎鼎的《算法（第 4 版）》，使用的是 <code>swim</code>（上浮）和 <code>sink</code>（下沉）：<a href="https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/MaxPQ.java.html" target="_blank" rel="noopener">https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/MaxPQ.java.html</a> 。</p>
<p>补充一下，之所以使用 <code>shift</code> 大家觉得没问题，是因为在解释这个操作的时候，一般都会用到 <code>shift</code> 这个词，顺便说一下，《算法导论》也避免了使用 sift/shift 的问题。但是《算法导论》取的名字非常不好，我个人不建议使用，比如用 <code>max-heapify</code> 表示下沉，完全没有体现出下沉这个动作。</p>
<p>结论：如果你对此特别在意，请使用 <code>sift</code> ，这应该是原始论文所用的名称；但其实，无所谓，完全不影响交流，也不会有人笑话你的。：）</p>
</blockquote>
<h3 id="基础堆排序和-Heapify"><a href="#基础堆排序和-Heapify" class="headerlink" title="基础堆排序和 Heapify"></a>基础堆排序和 Heapify</h3><p>这一节我们介绍两个使用堆或者说基于堆的思想进行排序的算法。</p>
<p>思路 1 ：一个一个地往最大堆里面放元素，然后再一个一个地取出，倒序放置于一个空数组中，就完成了元素的排序；</p>
<p>思路 2 ：一次性把整个数组复制到一个新数组，通过新数组 <code>heapify</code> 操作，使得新数组成为一个最大堆，然后再一个一个地取出，倒序放置于一个空数组中，就完成了元素的排序。</p>
<h3 id="思路-1：一个一个放进最大堆，再一个一个地取出完成排序"><a href="#思路-1：一个一个放进最大堆，再一个一个地取出完成排序" class="headerlink" title="思路 1：一个一个放进最大堆，再一个一个地取出完成排序"></a>思路 1：一个一个放进最大堆，再一个一个地取出完成排序</h3><p>我们首先要明确的是，堆排序的时间复杂度是 $O(n \log n)$。</p>
<p>我们可以从以下几个维度进行不同算法性能的比较，对数量级是 100 万个元素的数组进行排序。</p>
<p>使用的排序算法维度：归并排序，快速排序，三路快速排序，堆排序（借助额外空间的堆排序）。</p>
<p>元素特点维度：1、随机；2、几乎有序；3、含有大量相同元素的数组。</p>
<p>Java 代码：</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HeapSort1</span> <span class="token keyword">implements</span> <span class="token class-name">ISortAlgorithm</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"第 1 个版本的堆排序算法"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">sort</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span> length <span class="token operator">=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        MaxHeap maxHeap <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MaxHeap</span><span class="token punctuation">(</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            maxHeap<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span>arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> maxHeap<span class="token punctuation">.</span><span class="token function">extractMax</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们在上一小节，介绍了将一个元素 insert 到最大堆中，和从最大堆中取出一个元素，仅仅通过这两个操作，就可以完成排序任务。方法很简单，把待排序数组中的元素全部 insert 到最大堆里，然后再一个一个取出来，因为我们要按照升序排序，因此从后向前放置从最大堆中拿出的元素。</p>
<p>这个方法有一个缺点，那就是要使用和数组元素个数相等的最大堆空间，即空间复杂度是 $O(n)$。</p>
<p>而这一节我们要介绍的是一种直接使用堆的 <code>sift down</code> 方法完成排序任务的方法，这种方法使用 $O(1)$ 的空间复杂度，用于一个临时表变量的存储。</p>
<p>首先，我们介绍一个操作，名为 <code>heapify</code> 。</p>
<h3 id="思路-2-：一次性复制数组元素到新的数组，新数组自我调整成最大堆"><a href="#思路-2-：一次性复制数组元素到新的数组，新数组自我调整成最大堆" class="headerlink" title="思路 2 ：一次性复制数组元素到新的数组，新数组自我调整成最大堆"></a>思路 2 ：一次性复制数组元素到新的数组，新数组自我调整成最大堆</h3><h4 id="什么是-Heapify？"><a href="#什么是-Heapify？" class="headerlink" title="什么是 Heapify？"></a>什么是 Heapify？</h4><p>Heapify 是尝试将一整个数组构建成一个堆的方式，即通过调整自己，交换数组中的元素，就可以把自己整理成一个最大堆。</p>
<h4 id="理解-Heapify-关键的部分"><a href="#理解-Heapify-关键的部分" class="headerlink" title="理解 Heapify 关键的部分"></a>理解 Heapify 关键的部分</h4><ul>
<li>所有的叶子结点就是一个最大堆，此时每个堆中的元素只有 1 个；</li>
<li>当我们的使用的数组从下标 1 开始计数的前提下，第 1 个非叶子的结点的下标是 <code>index / 2</code>（自己画一个图，就可以看清楚这个规律，可以使用数学归纳法来证明），如何让它满足堆的性质呢？  <code>sift down</code> 就可以了。</li>
<li>思考：我们为什么不用  <code>sift up</code> ？<br>我的思考如下：如果使用 <code>sift up</code> 的话，那就得将数组中所有的元素都 <code>sift up</code>，相比于只用一半的元素 <code>sift down</code> 而言，工作量会少很多。</li>
<li>从 <code>index / 2</code> 递减到根（index==1的时候）依次去完成 <code>sift down</code>，一开始就排除了 <code>len / 2</code> 这么多元素。</li>
</ul>
<h3 id="heapify"><a href="#heapify" class="headerlink" title="heapify"></a>heapify</h3><p>使得一个数组是堆有序的操作就叫做  <code>heapify</code> 。具体的做法是：从最后一个非叶子结点开始到下标为 $0$ 的位置，逐个 <code>sift down</code>。</p>
<p>在上一步「堆排序」中，我们注意到，有这样一个操作：把待排序数组<strong>按顺序</strong>放入一个堆（入队），这一步得一个接着一个按照顺序放入堆中，实际上，可以通过一个称之为  <code>heapify</code>  的操作，让这个数组自行调整成一个最大堆，即使之「堆有序」，而此时无需借助 $O(n)$ 空间就完成了最大堆的构建。事实上，只需对数组中一半的元素执行 <code>sift down</code> 就可以了。</p>
<p>以下代码还是使用了  $O(n)$ 空间，主要是为了说明  <code>heapify</code> 。</p>
<p>heapify 如下所示：从下标的 <code>self.count // 2</code> 位置开始，直到索引为 $0$ 的元素结束，逐个下沉，就可以让一个数组堆有序。</p>
<p>说明：下标为 <code>self.count // 2</code> 位置是从下到上第 1 个非叶子结点的下标。</p>
<p>Java 代码：</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token comment" spellcheck="true">/**
 * 传递一个数组，形成一个最大堆
 * 理解 heapify 是关键
 *
 * @param arr 待排序的数组元素
 */</span>
<span class="token keyword">public</span> <span class="token function">MaxHeap</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">int</span> length <span class="token operator">=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
    data <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">int</span><span class="token punctuation">[</span>length <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        data<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment" spellcheck="true">// 添加一个元素，就要把 count 加 1 ，因为我们是一次性添加，所以就直接将 count 赋值为 length 就可以了</span>
    <span class="token comment" spellcheck="true">// 这一步赋值千万别忘了</span>
    count <span class="token operator">=</span> length<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">// 理解这一步是关键 heapify</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> length <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">siftDown</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Python 代码：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">MaxHeap</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> nums<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>capacity <span class="token operator">=</span> len<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>data <span class="token operator">=</span> <span class="token punctuation">[</span>None<span class="token punctuation">]</span> <span class="token operator">*</span> <span class="token punctuation">(</span>self<span class="token punctuation">.</span>capacity <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>count <span class="token operator">=</span> len<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>
        self<span class="token punctuation">.</span>__heapify<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__heapify</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> nums<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 挨个赋值</span>
        <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span>self<span class="token punctuation">.</span>capacity<span class="token punctuation">)</span><span class="token punctuation">:</span>
            self<span class="token punctuation">.</span>data<span class="token punctuation">[</span>i <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> nums<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
        <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span>self<span class="token punctuation">.</span>count <span class="token operator">//</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
            self<span class="token punctuation">.</span>__sift_down<span class="token punctuation">(</span>i<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这样，我们就可以写出我们的第 2 个使用堆排序的算法了，直接把数组传到最大堆这个数据结构里面。</p>
<p> <code>heapify</code>  以后挨个取出来，倒着放回去，也可以完成排序，就不用一个一个放进去，做上浮的操作了。整体上排序会比一个一个放进去快一些。</p>
<p>Java 代码：通过  <code>heapify</code>  将数组重组成最大堆实现的排序</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HeapSort2</span> <span class="token keyword">implements</span> <span class="token class-name">ISortAlgorithm</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"第 2 个版本的堆排序算法"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">sort</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        MaxHeap maxHeap <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MaxHeap</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> length <span class="token operator">=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> maxHeap<span class="token punctuation">.</span><span class="token function">extractMax</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>重要结论：堆排序在整体上的性能不如归并排序和快速排序。但是，堆这种数据结构更多的时候用于动态数据的维护。</p>
<p>一个数学结论：将 $n$ 个元素逐一插入到一个空堆中，时间复杂度是 $O(n \log n)$。 <code>heapify</code>  的过程，时间复杂度是 $O(n)$。</p>
<p>HeapSort2 会快一点的原因是：一上来我们从 <code>n / 2</code> 这个地方开始，逐一操作，排除了 n/2 个元素，所以效率肯定比第 1 种好。</p>
<p>可是这两种基于堆的排序算法，我们在堆排序的过程中，使用了额外的空间（即 <code>MaxHeap</code> 中的数组），使用了 $O(n)$ 的空间复杂度。那么不借助额外的空间是不是也可以完成堆排序呢？这就是我们下一节要介绍的内容——原地堆排序。</p>
<h3 id="原地堆排序"><a href="#原地堆排序" class="headerlink" title="原地堆排序"></a>原地堆排序</h3><p>通过上一节的学习，我们知道一个数组通过  <code>heapify</code>  操作，即通过一半的元素执行  <code>sift down</code>  的操作可以逐渐地整理成一个最大堆。</p>
<p>我们把「原地堆排序」拆解为以下 3 个部分：</p>
<p>1、首先，转换思维，堆从数组下标 $0$ 开始编号；</p>
<p>代码很多地方都要改，好在并不复杂，正好可以帮助我们复习堆的 <code>sift down</code> 操作，如果只是用于排序任务，不需要 <code>sift up</code> 操作；</p>
<p>2、  <code>sift down</code>  操作要设计成如下的样子，设计一个表示 <code>end</code> 的变量，表示待排序数组的 <code>[0, end]</code>（注意是闭区间）范围是堆有序的。</p>
<p>上一节我们将一个数组通过   <code>heapify</code>   的方式逐渐地整理成一个最大堆。而原地堆排序的思想是非常直观的，从  <code>sift down</code> 的操作我们就可以得到启发，堆中最大的那个元素在数组的 0 号索引位置，我们把它与此时数组中的最后一个元素交换，那么数组中最大的元素就放在了数组的末尾，此时再对数组的第一个元素执行  <code>sift down</code> ，那么  <code>sift down</code>  操作都执行完以后，数组的第 1 个元素就存放了当前数组中的第 2 大的元素。依次这样做下去，就可以将一个数组进行排序。</p>
<p>理解这个原理的关键之处：对堆顶元素执行了 <code>sift down</code> 操作以后，就会把这个堆中的最大的元素挪到堆顶。</p>
<p>此时，因为用到了下标，并且须要用到下标为 $0$ 的数组元素，因此我们就要将最大堆中数组的下标从 $0$ 开始计算，重新写一套堆的 API。</p>
<p>我们整理一下，其实这个思想跟「选择排序」是一样的，只不过我们每一轮选出一个当前未排定的数中最大的那个，即：「选择排序」 + 「堆」 就是「堆排序」。</p>
<p><img src="https://liweiwei1419.github.io/images/algorithms/%E5%8E%9F%E5%9C%B0%E5%A0%86%E6%8E%92%E5%BA%8F%E7%A4%BA%E6%84%8F%E5%9B%BE.jpg" alt="堆排序、heapify、原地堆排序-1"></p>
<p>「堆排序」代码实现的注意事项：</p>
<p>1、此时最大堆中数组的下标从 $0$ 开始计算。与之前下标从 $1$ 开始的最大堆实现比较，性质就发生了变化，但并不会不好找，我们可以自己在纸上画一个完全二叉树就可以很清晰地发现规律：</p>
<ul>
<li>${\rm parent}(i)=\cfrac{i-1}{2}$；</li>
<li>${\rm left \quad child}(i) = 2 \times i +1$；</li>
<li>${\rm right \quad child}(i) = 2 \times i +2$；</li>
<li>最后一个非叶子结点的索引是：$\cfrac{count-1}{2}$；</li>
</ul>
<p>2、原地堆排序，因为下标从 $0$ 号开始，相应的一些性质在索引上都发生变化了；</p>
<p>3、注意到我们只有 <code>sift down</code> 的操作，对于 <code>sift down</code> 的实现，一些细节就要很小心， <code>sift down</code> 是在一个区间内进行的，我们在设计新的 <code>sift down</code> 方法的实现的时候，应该设计待排序数组区间的右端点。</p>
<p>Java 代码：</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token comment" spellcheck="true">/**
 * 原地堆排序
 * Created by liwei on 17/5/15.
 */</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HeapSort3</span> <span class="token keyword">implements</span> <span class="token class-name">ISortAlgorithm</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"原地堆排序"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>


    <span class="token comment" spellcheck="true">/**
     * 原地堆排序的目标就是，不再借助 MaxHeap 这个数据结构进行排序，减少了空间复杂度
     * 注意：此时我们的数组索引从 0 开始定义(自己在纸上画一下图，就能清晰地明白算法实现的含义)
     *
     * @param arr 待排序数组
     */</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">sort</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span> length <span class="token operator">=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 将一个无序的数组组成了一个最大堆，第 1 个元素就是最大值</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token punctuation">(</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">siftDown</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> length<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment" spellcheck="true">// 代码逻辑非常简单明确，完全可以自己写出来</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">swap</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">siftDown</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> i<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>


    <span class="token comment" spellcheck="true">/**
     * 从索引为 0 开始，up 为止 [0,up] 的数组元素进行 shift down 的操作
     *
     * @param arr 
     * @param up 这里的 up 定义为形成堆这个数据结构的最大下标（从索引 0 就放元素），
     *           即在区间 [0,up] 范围内 Shift Down
     * @param index 对索引是 index 的元素执行 Shift Down 操作
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">siftDown</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">,</span> <span class="token keyword">int</span> up<span class="token punctuation">,</span> <span class="token keyword">int</span> index<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">// 如果有右孩子的结点，并且右孩子结点比左孩子结点的值要大</span>
        <span class="token comment" spellcheck="true">// 此时可以忽略左孩子结点的存在，拿右孩子结点的数值和自己比较</span>

        <span class="token comment" spellcheck="true">// 只要它有左孩子，就不是叶子结点，就可能 shift down，注意：这里是小于号</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token number">2</span> <span class="token operator">*</span> index <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">&lt;</span> up<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">2</span> <span class="token operator">*</span> index <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>j <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">&lt;</span> up <span class="token operator">&amp;&amp;</span> arr<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">&lt;</span> arr<span class="token punctuation">[</span>j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                j <span class="token operator">=</span> j <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>arr<span class="token punctuation">[</span>index<span class="token punctuation">]</span> <span class="token operator">&lt;</span> arr<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token function">swap</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> index<span class="token punctuation">,</span> j<span class="token punctuation">)</span><span class="token punctuation">;</span>
                index <span class="token operator">=</span> j<span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// 留意</span>
            <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">swap</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr<span class="token punctuation">,</span> <span class="token keyword">int</span> index1<span class="token punctuation">,</span> <span class="token keyword">int</span> index2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span> temp <span class="token operator">=</span> arr<span class="token punctuation">[</span>index1<span class="token punctuation">]</span><span class="token punctuation">;</span>
        arr<span class="token punctuation">[</span>index1<span class="token punctuation">]</span> <span class="token operator">=</span> arr<span class="token punctuation">[</span>index2<span class="token punctuation">]</span><span class="token punctuation">;</span>
        arr<span class="token punctuation">[</span>index2<span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Python 代码：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">__sift_down</span><span class="token punctuation">(</span>nums<span class="token punctuation">,</span> end<span class="token punctuation">,</span> k<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># end ：数组 nums 的尾索引，</span>
    <span class="token comment" spellcheck="true"># __sink 方法维持 nums[0:end]，包括 nums[end] 在内堆有序</span>
    <span class="token keyword">assert</span> k <span class="token operator">&lt;=</span> end
    temp <span class="token operator">=</span> nums<span class="token punctuation">[</span>k<span class="token punctuation">]</span>
    <span class="token keyword">while</span> <span class="token number">2</span> <span class="token operator">*</span> k <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">&lt;=</span> end<span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 只要有孩子结点：有左孩子，就要孩子结点</span>
        t <span class="token operator">=</span> <span class="token number">2</span> <span class="token operator">*</span> k <span class="token operator">+</span> <span class="token number">1</span>
        <span class="token keyword">if</span> t <span class="token operator">+</span> <span class="token number">1</span> <span class="token operator">&lt;=</span> end <span class="token operator">and</span> nums<span class="token punctuation">[</span>t<span class="token punctuation">]</span> <span class="token operator">&lt;</span> nums<span class="token punctuation">[</span>t <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true"># 如果有右边的结点，并且右结点还比左结点大</span>
            t <span class="token operator">+=</span> <span class="token number">1</span>
        <span class="token keyword">if</span> nums<span class="token punctuation">[</span>t<span class="token punctuation">]</span> <span class="token operator">&lt;=</span> temp<span class="token punctuation">:</span>
            <span class="token keyword">break</span>
        nums<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">=</span> nums<span class="token punctuation">[</span>t<span class="token punctuation">]</span>
        k <span class="token operator">=</span> t
    nums<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">=</span> temp


<span class="token keyword">def</span> <span class="token function">__heapy</span><span class="token punctuation">(</span>nums<span class="token punctuation">)</span><span class="token punctuation">:</span>
    l <span class="token operator">=</span> len<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>
    <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token punctuation">(</span>l <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">//</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        __sift_down<span class="token punctuation">(</span>nums<span class="token punctuation">,</span> l <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>


<span class="token keyword">def</span> <span class="token function">heap_sort</span><span class="token punctuation">(</span>nums<span class="token punctuation">)</span><span class="token punctuation">:</span>
    l <span class="token operator">=</span> len<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>
    __heapy<span class="token punctuation">(</span>nums<span class="token punctuation">)</span>

    <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span>l <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        nums<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> nums<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> nums<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> nums<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span>
        __sift_down<span class="token punctuation">(</span>nums<span class="token punctuation">,</span> i <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>说明：首先进行一次 <code>heapify</code> 的过程：从索引为 $\cfrac{count-1}{2}$ 的结点开始执行 <code>shift down</code>。<code>heapify</code> 过程的代码框架几乎是套路，一定要熟悉，只不过我们要弄清楚，我们的最大堆是从索引为 $0$ 的位置开始存放元素，还是从索引为 $1$ 的地方开始存放元素。</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token comment" spellcheck="true">// 将一个无序的数组组成了一个最大堆，第 1 个元素就是最大值</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token punctuation">(</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">siftDown</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> length<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>到此为止，堆的排序算法就已经介绍完了，下面我们对之前学习过的排序算法作一个总结。</p>
<h2 id="排序算法总结"><a href="#排序算法总结" class="headerlink" title="排序算法总结"></a>排序算法总结</h2><h3 id="平均时间复杂度"><a href="#平均时间复杂度" class="headerlink" title="平均时间复杂度"></a>平均时间复杂度</h3><p>时间复杂度分为平均时间复杂度、最好时间复杂度和最坏时间复杂度。对于一个算法来说，往往有很多特殊情况，一般而言，我们所说的时间复杂度都指最坏时间复杂度。</p>
<h3 id="对我们学习过的各种排序算法的总结和对比"><a href="#对我们学习过的各种排序算法的总结和对比" class="headerlink" title="对我们学习过的各种排序算法的总结和对比"></a>对我们学习过的各种排序算法的总结和对比</h3><p>快速排序相对会更快一些。一般系统级别的排序，是用快速实现的。如果有大量重复键值，可以使用三路快排。</p>
<h3 id="排序算法的稳定性"><a href="#排序算法的稳定性" class="headerlink" title="排序算法的稳定性"></a>排序算法的稳定性</h3><p>查资料了解什么是排序算法的稳定性。可以通过自定义比较函数，让排序算法不存在稳定性问题。系统级别的排序算法，如果要求稳定性的话，一般使用归并排序。</p>
<h3 id="对未来的探索"><a href="#对未来的探索" class="headerlink" title="对未来的探索"></a>对未来的探索</h3><p>是不是存在一种神秘的排序算法？让所有指标达到最优呢。liuyubobobo 老师告诉我们，目前还没有。</p>
<h3 id="本文源代码"><a href="#本文源代码" class="headerlink" title="本文源代码"></a>本文源代码</h3><ul>
<li>Java：<a href="https://github.com/liweiwei1419/Algorithms-Learning-Java/tree/master/06-Heap/src" target="_blank" rel="noopener">代码文件夹</a>；</li>
<li>Python：<a href="https://github.com/liweiwei1419/Algorithms-Learning-Python/tree/master/heap" target="_blank" rel="noopener">代码文件夹</a>。</li>
</ul>
<p>（本节完）</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" rel="external nofollow noreferrer">liwei</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/2017/10/02/algorithms-and-data-structures/heapify-and-heap-sort/">https://liweiwei1419.gitee.io/leetcode-algo/2017/10/02/algorithms-and-data-structures/heapify-and-heap-sort/</a>
                    <!-- GitHub 用配置
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2017/10/02/algorithms-and-data-structures/heapify-and-heap-sort/">https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2017/10/02/algorithms-and-data-structures/heapify-and-heap-sort/</a>
                    -->
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明：
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liwei</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/leetcode-algo/tags/%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97/">
                                    <span class="chip bg-color">优先队列</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/leetcode-algo/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/leetcode-algo/medias/reward/alipayimg.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/leetcode-algo/medias/reward/wechatpayimg.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/leetcode-algo/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/leetcode-algo/libs/valine/av-min.js"></script>
<script src="/leetcode-algo/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 't85BdPqKV8IDpevPmRGUSquP-gzGzoHsz',
        appKey: 'AIarytPiYajpQ31kGdAMfVQ8',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/leetcode-algo/2017/10/02/leetcode-solution/0102-binary-tree-level-order-traversal/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/12.jpg" class="responsive-img" alt="「力扣」第 102 题：二叉树的层次遍历">
                        
                        <span class="card-title">「力扣」第 102 题：二叉树的层次遍历</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「力扣」第 102 题：二叉树的层次遍历传送门：102. 二叉树的层次遍历。

给定一个二叉树，返回其按层次遍历的节点值。 （即逐层地，从左到右访问所有节点）。
例如:给定二叉树: [3,9,20,null,null,15,7],
3
/ 
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2017-10-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-9%EF%BC%9A%E9%98%9F%E5%88%97/" class="post-category">
                                    专题 9：队列
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E9%98%9F%E5%88%97/">
                        <span class="chip bg-color">队列</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/leetcode-algo/2017/10/01/leetcode-solution/queue-1/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/18.jpg" class="responsive-img" alt="「队列」专题：队列与广度优先遍历">
                        
                        <span class="card-title">「队列」专题：队列与广度优先遍历</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「队列」专题：队列与广度优先遍历队列 Queue 主要处理的问题是广度优先遍历（不论是针对树还是图，可以把树理解为图的特殊形式）。

                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2017-10-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-9%EF%BC%9A%E9%98%9F%E5%88%97/" class="post-category">
                                    专题 9：队列
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E9%98%9F%E5%88%97/">
                        <span class="chip bg-color">队列</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/leetcode-algo/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liweiwei1419</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/liweiwei1419" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:liweiwei1419@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=121088825" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 121088825" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="https://weibo.com/u/2194939432" class="tooltipped" target="_blank" data-tooltip="关注我的微博: https://weibo.com/u/2194939432" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/leetcode-algo/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/leetcode-algo/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/leetcode-algo/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/leetcode-algo/libs/materialize/materialize.min.js"></script>
    <script src="/leetcode-algo/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/leetcode-algo/libs/aos/aos.js"></script>
    <script src="/leetcode-algo/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/leetcode-algo/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/leetcode-algo/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/leetcode-algo/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/leetcode-algo/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/leetcode-algo/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
